package com.flashcash.solu.view.fragment.presenter;


import android.util.Pair;

import com.appsflyer.AppsFlyerLib;
import com.flashcash.solu.R;
import com.flashcash.solu.bean.ApplyLoanInfo;
import com.flashcash.solu.bean.ApplySkypayLoanInfo;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.ResponseErrorBody;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.common.network.HttpErrorHandledSubScriber;
import com.flashcash.solu.common.network.ServiceGenerator;
import com.flashcash.solu.common.network.UserApi;
import com.flashcash.solu.harvester.TraceSender;
import com.flashcash.solu.view.camera.FaceDetectorPreImpl;
import com.flashcash.solu.view.fragment.LoaningFraView;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.google.gson.Gson;
import com.flashcash.kotlin.data.BankBean;
import com.flashcash.kotlin.data.LoaningAmoutBean;
import com.flashcash.kotlin.data.UserBankInfo;
import com.flashcash.kotlin.data.WithdrawChannel;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.log.XLog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * @作者:My
 * @创建日期: 2017/6/21 15:40
 * @描述:${TODO}
 * @更新者:${Author}$
 * @更新时间:${Date}$
 * @更新描述:${TODO}
 */

public class LoaningFraPreImp extends FaceDetectorPreImpl implements LoaningFraPresenter {
    private final UserApi api = ServiceGenerator.createService(UserApi.class);

    @Override
    public void applyLoan(final ApplyLoanInfo applyLoanInfo) {
        final LoaningFraView view = (LoaningFraView) mView;
        showLoading(null);
//        depresd(applyLoanInfo, view);
        if (TokenManager.getInstance().hasLogin()) {
            mUserApi.addBank(applyLoanInfo.getLoanAppId(),
                    applyLoanInfo.getBankCode(),
                    applyLoanInfo.getCardNo(),
                    applyLoanInfo.getApplyFor(),
                    applyLoanInfo.getCardMonth(),
                    applyLoanInfo.getCardYear(),
                    applyLoanInfo.getFullName(),
                    applyLoanInfo.getEmail(),
                    applyLoanInfo.getApplyChannel(),
                    "ANDROID",
                    applyLoanInfo.getCouponId(),
                    TokenManager.getInstance().getToken())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new HttpErrorHandledSubScriber<ResponseBody>() {

                        @Override
                        public void onFinalError(Throwable throwable) {
                            dismissLoading();
                            if (isAttached()) {
                                view.addBankError(throwable);
                            }
                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            dismissLoading();
                            if (isAttached()) {
                                view.addBankSuccess();
                            }
                        }
                    });
        } else {
            if (isAttached()) {
                mView.toLogin();
            }
        }

    }

    @Override
    public void applySkypayLoan(ApplySkypayLoanInfo applyLoanInfo) {
        final LoaningFraView view = (LoaningFraView) mView;
        showLoading(null);
//        depresd(applyLoanInfo, view);
        if (TokenManager.getInstance().hasLogin()) {
            mUserApi.addSkypayInfo(applyLoanInfo.getLoanAppId(), applyLoanInfo.getWithDrawChannel(),
                    applyLoanInfo.getAccountNo(), applyLoanInfo.getBankNo(),
                    applyLoanInfo.getBankProvince(), applyLoanInfo.getBankCity(),
                    TokenManager.getInstance().getToken())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new HttpErrorHandledSubScriber<ResponseBody>() {

                        @Override
                        public void onFinalError(Throwable throwable) {
                            dismissLoading();
                            if (isAttached()) {
                                view.addBankError(throwable);
                            }
                        }

                        @Override
                        public void onNext(ResponseBody responseBody) {
                            dismissLoading();

                            if (isAttached()) {
                                view.addBankSuccess();

                            }

                            Map<String,Object> eventValues = new HashMap<>();
                            eventValues.put("loan_app_id", applyLoanInfo.getLoanAppId());
                            AppsFlyerLib.getInstance().trackEvent(mView.getBaseActivity().getBaseContext(), "af_apply", eventValues);
                        }
                    });
        } else {
            if (isAttached()) {
                mView.toLogin();
            }
        }

    }

    private void depresd(ApplyLoanInfo applyLoanInfo, final LoaningFraView view) {
        api.applyLoanApp(applyLoanInfo.getLoanType(),
                applyLoanInfo.getAmount() + "",
                applyLoanInfo.getPeroid() + "",
                applyLoanInfo.getPeriodUnit(),
                applyLoanInfo.getBankCode(),
                applyLoanInfo.getCardNo().trim(),
                applyLoanInfo.getApplyFor(),
                applyLoanInfo.getApplyChannel(),
                applyLoanInfo.getApplyPlatform(),
                applyLoanInfo.getCouponId(),
                TokenManager.getInstance().getToken()
                , TraceSender.getAndroidID(mView.getBaseActivity().getApplicationContext())
        ).flatMap(new Func1<ResponseBody, Observable<LatestLoanAppBean>>() {
            @Override
            public Observable<LatestLoanAppBean> call(ResponseBody responseBody) {
                return mUserApi.getLatestLoanApp(TokenManager.getInstance().getToken(), "loaning");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LatestLoanAppBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Gson gson = new Gson();
                        if (e instanceof HttpException) {
                            HttpException httpException = (HttpException) e;
                            String errorBody;
                            try {
                                errorBody = httpException.response().errorBody().string();
                                ResponseErrorBody responseErrorBody = gson.fromJson(errorBody,
                                        ResponseErrorBody.class);
                                XLeoToast.showMessage(responseErrorBody.getMessage());
                                XLog.INSTANCE.d("e:" + errorBody, 10);
                            } catch (Exception e1) {
                                // Gson throws JsonSyntaxException & response.body throws
                                // IOException
                                e1.printStackTrace();
                            }

                        } else {
                            XLeoToast.showMessage(e.toString());
                            XLog.INSTANCE.e("e:", e, 100);
                        }
                        dismissLoading();
                        if (isAttached()) {
                            view.resetButton();
                        }

                    }

                    @Override
                    public void onNext(LatestLoanAppBean responseBody) {
                        XLog.INSTANCE.d(" reSet video recording", 10);
                        if (isAttached()) {
                            if (responseBody != null && responseBody.getLoanAppId() != null) {
                                CacheDataManage.INSTANCE.addData(FieldParamsInt.LATESTBEAN,
                                        responseBody);
                                view.onApplyLoanSuccess();
                            } else {
                                dismissLoading();
                                view.resetButton();
                            }
                        }
                    }
                });
    }

    @Override
    public void requestLoanInfo() {
        showLoading("");
        if (TokenManager.getInstance().hasLogin()) {
            mUserApi.getLatestLoanApp(TokenManager.getInstance().getToken(), "loaningFragment")
                    .subscribeOn(Schedulers.io())
                    .flatMap(new Func1<LatestLoanAppBean, Observable<Pair<Pair<LatestLoanAppBean,
                            LoaningAmoutBean>, UserBankInfo>>>() {
                        @Override
                        public Observable<Pair<Pair<LatestLoanAppBean, LoaningAmoutBean>,
                                UserBankInfo>> call(LatestLoanAppBean latestLoanAppBean) {
                            if (latestLoanAppBean != null && FieldParams.LoanStatus.SUBMITTED
                                    .equals(latestLoanAppBean.getStatus())) {
                                return Observable.combineLatest(Observable.just(latestLoanAppBean),
                                        mUserApi.getLoanAmoutData(latestLoanAppBean.getAmount(),
                                                latestLoanAppBean.getPeriod(),
                                                latestLoanAppBean.getPeriodUnit(),
                                                latestLoanAppBean.getProductId()),
                                        mUserApi.getBankCardInfo(TokenManager.getInstance().getToken()), (latestLoanAppBean1, loaningAmoutBean, bankInfo) -> new Pair<>(new Pair<>(latestLoanAppBean1, loaningAmoutBean), bankInfo));
                            } else {
                                return Observable.just(new Pair<Pair<LatestLoanAppBean,
                                        LoaningAmoutBean>, UserBankInfo>(new Pair<>(null, null),
                                        null));
                            }
                        }
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<Pair<Pair<LatestLoanAppBean, LoaningAmoutBean>,
                            UserBankInfo>>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable throwable) {
                            dismissLoading();
                            XLeoToast.showMessage(R.string.network_error);
                            if (isAttached()) {
                                ((LoaningFraView) mView).onAmountObtainError(throwable);
                            }
                        }

                        @Override
                        public void onNext
                                (Pair<Pair<LatestLoanAppBean, LoaningAmoutBean>, UserBankInfo> it) {
                            dismissLoading();
                            if (isAttached() && it.first != null && it.first.first != null && it
                                    .first.second != null) {
                                ((LoaningFraView) mView).onAmountObtain(it);
                            }
                        }
                    });
        } else {
            if (isAttached()) {
                mView.toLogin();
            }
        }


    }

    @Override
    public void requestBankList(String type) {
        showLoading("");
        mUserApi.requestBankList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpErrorHandledSubScriber<List<BankBean>>() {
                    @Override
                    public void onFinalError(Throwable e) {
                        dismissLoading();
                        if (isAttached()) {
                            ((LoaningFraView) mView).onBankRequestError(e);
                        }
                    }

                    @Override
                    public void onNext(List<BankBean> bankBeans) {
                        dismissLoading();
                        if (bankBeans != null && bankBeans.size() > 0) {
                            if (isAttached()) {
                                ((LoaningFraView) mView).onBankRequestSuccess(type, bankBeans);
                            }
                        } else {
                            onFinalError(new IllegalStateException("empty bank list"));
                        }

                    }
                });

    }

    @Override
    public void requestWithdrawChannels() {
        showLoading("");
        mUserApi.getSkyPayWithdrawChannles(4)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpErrorHandledSubScriber<List<WithdrawChannel>>() {
                    @Override
                    public void onFinalError(Throwable e) {
                        dismissLoading();
                        if (isAttached()) {
                            ((LoaningFraView) mView).onWithdrawChnanleRequestError(e);
                        }
                    }

                    @Override
                    public void onNext(List<WithdrawChannel> withdrawChannels) {
                        dismissLoading();
                        if (withdrawChannels != null && withdrawChannels.size() > 0) {
                            if (isAttached()) {
                                for(int i = 0; i < withdrawChannels.size(); i++){
                                    if(withdrawChannels.get(i).getName().equals("GCash")){
                                        withdrawChannels.get(i).setName("GCash(preferred)");
                                    }
                                }
                                ((LoaningFraView) mView).setWithdrawChannels(withdrawChannels);
                                ((LoaningFraView) mView).onWithdrawChannelRequestSuccess(withdrawChannels);
                            }
                        } else {
                            onFinalError(new IllegalStateException("empty bank list"));
                        }
                    }
                });
    }

}
